<template>
  <div class="home">
    <van-nav-bar title="购物车" left-text="返回" right-text="按钮" left-arrow />
    <van-swipe-cell v-for="(item, index) in list" :key="index">
      <van-checkbox v-model="item.isCheck" @change="check"></van-checkbox>
      <van-card
        :num="item.num"
        :price="item.price"
        :desc="item.desc"
        :title="item.name"
        :thumb="item.url"
      >
        <template #footer>
          <van-button size="mini" @click="reduce(item)">-</van-button>
          <van-button size="mini" @click="add(item)">+</van-button>
        </template>
      </van-card>
      <template #right>
        <van-button
          @click="del(index)"
          square
          text="删除"
          type="danger"
          class="delete-button"
        />
      </template>
    </van-swipe-cell>
    <van-submit-bar :price="allPrice" button-text="提交订单">
      <van-checkbox v-model="checked" @click="allCheck">全选</van-checkbox>
    </van-submit-bar>
  </div>
</template>

<script>
// @ is an alias to /src

export default {
  name: "Home",
  data() {
    return {
      list: [
        {
          name: "华为",
          desc: "支持国产用华为",
          price: 4999,
          num: 10,
          url: "https://img01.yzcdn.cn/vant/ipad.jpeg",
          isCheck: false,
        },
        {
          name: "小米",
          desc: "为发烧而生",
          price: 3999,
          num: 1,
          url: "https://img01.yzcdn.cn/vant/ipad.jpeg",
          isCheck: false,
        },
        {
          name: "三星",
          desc: "爆炸就是艺术",
          price: 6999,
          num: 1,
          url: "https://img01.yzcdn.cn/vant/ipad.jpeg",
          isCheck: false,
        },
        {
          name: "诺基亚",
          desc: "耐用就够了",
          price: 1999,
          num: 10,
          url: "https://img01.yzcdn.cn/vant/ipad.jpeg",
          isCheck: false,
        },
      ],
      checked: false,
    };
  },
  computed: {
    // 计算属性
    allPrice() {
      let num = 0;
      this.list.forEach((item) => {
        if (item.isCheck) {
          num += item.price * item.num;
        }
      });
      return num * 100;
    },
  },
  methods: {
    allCheck() {
      // 点击全选改变的事件
      // console.log();
      this.list.forEach((item) => {
        item.isCheck = this.checked;
      });
    },
    check() {
      // 点击反选改变的事件
      this.checked = this.list.every((item) => item.isCheck);
    },
    reduce(val) {
      // val 是一个对象 利用的是引用数据类型的特性
      if (val.num == 1) {
        return;
      }
      val.num--;
    },
    add(val) {
      // val 是一个对象 利用的是引用数据类型的特性
      val.num++;
    },
    del(i) {
      this.list.splice(i, 1);
    },
  },
};
</script>
<style lang="scss">
.home {
  background: #ccc;
  height: 100%;
}
.van-swipe-cell__wrapper {
  display: flex;
  background: #fff;
}
.van-card {
  flex: 1;
}
.van-checkbox {
  padding: 10px;
}
.delete-button.van-button{
  height: 100%;
}
</style>
